package com.central.apps.handler.project;

import com.central.app.common.base.BaseHandler;
import com.central.app.common.cache.CfgRedisCache;
import com.central.app.model.BizApp;
import com.central.app.service.HandlerService;
import com.central.apps.entity.BlMessage;
import com.central.apps.service.MessageService;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.util.SysUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 处理问题管理业务逻辑
 *
 * @author lidachao
 * @date 2023/5/19
 */
@Component
@Slf4j
public class ProjectProblemHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CfgRedisCache cfgRedisCache;

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        // 确认问题
        if ("quoteproproblemApp".equals(app) && "gq_proproblem".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");
            LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String strDate = sdf.format(new Date(System.currentTimeMillis()));

            String confirmCcToIds = MapUtils.getString(data, "confirmcctoids");
            String confirmCcTo = MapUtils.getString(data, "confirmccto");
            String confirmRemarks = MapUtils.getString(data, "confirmremarks");

            // 组织操作记录信息
            StringBuilder sb = new StringBuilder();
            sb.append(strDate).append(", 由").append(loginUser.getUsername()).append("确认问题");

            Map<String, Object> map = new HashMap<>();
            map.put("ppid", id);
            map.put("recorddesc", sb.toString());
            map.put("recordremarks", confirmRemarks);

            // 插入操作记录信息
            BigInteger pprId = (BigInteger) handlerService.insert("gq_proproblemrecord", map);

            // 组织记录变更信息
            Map<String, Object> oldMap = handlerService.findOneBySql("select * from gq_proproblem where id = " + id);
            List<String> filterFields = new ArrayList<>();
            filterFields.add("problemtype");
            filterFields.add("property");
            filterFields.add("influence");
            filterFields.add("complexity");
            filterFields.add("importance");
            filterFields.add("priority");

            // 比较并组织记录变更信息
            List<Map<String, Object>> addList = new ArrayList<>();
            StringBuilder content = new StringBuilder();
            for (Map.Entry<String, Object> oldEntry : oldMap.entrySet()) {
                if (filterFields.contains(oldEntry.getKey())) {
                    for (Map.Entry<String, Object> entry : data.entrySet()) {
                        if (filterFields.contains(entry.getKey()) && !oldEntry.getValue().equals(entry.getValue())) {
                            Map<String, Object> addMap = new HashMap<>();
                            StringBuilder chgInfo = new StringBuilder();

                            String fieldName = "";
                            switch (entry.getKey()) {
                                case "problemtype":
                                    fieldName = "问题类型";
                                    break;
                                case "property":
                                    fieldName = "性质";
                                    break;
                                case "influence":
                                    fieldName = "影响度";
                                    break;
                                case "complexity":
                                    fieldName = "复杂度";
                                    break;
                                case "importance":
                                    fieldName = "重要性";
                                    break;
                                case "priority":
                                    fieldName = "优先级";
                                    break;
                                default:
                                    break;
                            }

                            chgInfo.append("修改了").append("\"").append(fieldName).append("\", ").append("旧值为\"").append(oldEntry.getValue()).append("\", ")
                                    .append("新值为\"").append(entry.getValue()).append("\"");
                            addMap.put("pprid", pprId);
                            addMap.put("upddetail", chgInfo.toString());

                            content.append("<p>").append(chgInfo.toString()).append("<p>");
                            addList.add(addMap);
                        }
                    }
                }
            }

            // 批量插入记录变更信息
            if (CollectionUtils.isNotEmpty(addList)) {
                handlerService.batchInsert("proproblemApp", "gq_proproblemupdrecord", addList);
            }

            // 发送消息通知
            if (StringUtils.isNotEmpty(confirmCcToIds)) {
                // 通知任务负责人
                BlMessage message = new BlMessage();

                StringBuilder msgTitle = new StringBuilder();
                String problemNum = MapUtils.getString(data, "problemnum");
                String title = MapUtils.getString(data, "title");
                msgTitle.append(title).append(": ").append(problemNum).append("由").append(loginUser.getUsername()).append("确认");

                message.setTitle(msgTitle.toString());

                if (StringUtils.isNotEmpty(content)) {
                    StringBuilder res = new StringBuilder();
                    res.append("<p>变更明细: <p>").append(content.toString()).append("<p>").append(confirmRemarks).append("<p>");
                    message.setContent(content.toString());
                }

                message.setIsshow("未读");
                message.setCreateuser("0");
                message.setCreateuserdesc("系统");

                if (StringUtils.isNotEmpty(confirmCcToIds)) {
                    String[] assignsArray = confirmCcToIds.split(",");
                    String[] assignsDescArray = confirmCcTo.split(",");
                    for (int i = 0; i < assignsArray.length; i++) {
                        // 通知抄送人员
                        message.setRecipient(assignsArray[i]);
                        message.setRecipientname(assignsDescArray[i]);
                        messageService.addMessage(message);
                    }
                }
            }
        }

        // 指派问题
        if ("quoteproproblem3App".equals(app) && "gq_proproblem".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");
            LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String strDate = sdf.format(new Date(System.currentTimeMillis()));
            String assignToName = MapUtils.getString(data, "assigntoname");
            String assignRemarks = MapUtils.getString(data, "assignremarks");

            // 组织操作记录信息
            StringBuilder sb = new StringBuilder();
            sb.append(strDate).append(", 由").append(loginUser.getUsername()).append("指派给").append(assignToName);

            Map<String, Object> map = new HashMap<>();
            map.put("ppid", id);
            map.put("recorddesc", sb.toString());
            map.put("recordremarks", assignRemarks);

            // 插入操作记录信息
            BigInteger pprId = (BigInteger) handlerService.insert("gq_proproblemrecord", map);

            // 查询问题记录
            Map<String, Object> oldMap = handlerService.findOneBySql("select assigntoname from gq_proproblem where id = " + id);
            String oldAssignToName = MapUtils.getString(oldMap, "assigntoname");

            // 组织并插入记录变更信息
            Map<String, Object> addMap = new HashMap<>();
            StringBuilder chgInfo = new StringBuilder();
            chgInfo.append("修改了").append("\"指派给\", ").append("旧值为\"").append(oldAssignToName).append("\", ")
                    .append("新值为\"").append(assignToName).append("\"");
            addMap.put("pprid", pprId);
            addMap.put("upddetail", chgInfo.toString());
            handlerService.insert("gq_proproblemupdrecord", addMap);
        }

        // 解决问题
        if ("quoteproproblem1App".equals(app) && "gq_proproblem".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");
            LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
            String actresolvedate = MapUtils.getString(data, "actresolvedate");
            String assignToName = MapUtils.getString(data, "assigntoname");
            String resolveRemarks = MapUtils.getString(data, "resolveremarks");

            // 组织操作记录信息
            StringBuilder sb = new StringBuilder();
            sb.append(actresolvedate).append(", 由").append(loginUser.getUsername()).append("解决");

            Map<String, Object> map = new HashMap<>();
            map.put("ppid", id);
            map.put("recorddesc", sb.toString());
            map.put("recordremarks", resolveRemarks);

            // 插入操作记录信息
            BigInteger pprId = (BigInteger) handlerService.insert("gq_proproblemrecord", map);

            // 查询问题记录
            Map<String, Object> oldMap = handlerService.findOneBySql("select assigntoname from gq_proproblem where id = " + id);
            String oldAssignToName = MapUtils.getString(oldMap, "assigntoname");

            // 组织并插入记录变更信息
            Map<String, Object> addMap = new HashMap<>();
            StringBuilder chgInfo = new StringBuilder();
            chgInfo.append("修改了").append("\"指派给\", ").append("旧值为\"").append(oldAssignToName).append("\", ")
                    .append("新值为\"").append(assignToName).append("\"");
            addMap.put("pprid", pprId);
            addMap.put("upddetail", chgInfo.toString());
            handlerService.insert("gq_proproblemupdrecord", addMap);

            addMap = new HashMap<>();
            chgInfo = new StringBuilder();
            chgInfo.append("修改了").append("\"实际解决日期\", ").append("新值为\"").append(actresolvedate).append("\"");
            addMap.put("pprid", pprId);
            addMap.put("upddetail", chgInfo.toString());
            handlerService.insert("gq_proproblemupdrecord", addMap);
        }
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        // 确认问题
        if ("quoteproproblemApp".equals(app) && "gq_proproblem".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");
            // 更新问题状态
            handlerService.updateBySql("update gq_proproblem set status = '已确认' where id = " + id);
        }

        // 提交问题
        if ("proproblemApp".equals(app) && "gq_proproblem".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");
            LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
            StringBuilder sb = new StringBuilder();
            String dateTime = "";
            String operate = "";
            if (isUpdate) {
                dateTime = MapUtils.getString(data, "updatetime");
                operate = "编辑";
            } else {
                dateTime = MapUtils.getString(data, "createtime");
                operate = "创建";
            }

            sb.append(dateTime).append(", 由").append(loginUser.getUsername()).append(operate);

            Map<String, Object> map = new HashMap<>();
            map.put("ppid", id);
            map.put("recorddesc", sb.toString());

            handlerService.insert("gq_proproblemrecord", map);
        }

        // 关闭问题
        if ("quoteproproblem2App".equals(app) && "gq_proproblem".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");
            LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String strDate = sdf.format(new Date(System.currentTimeMillis()));
            String closeRemarks = MapUtils.getString(data, "closeremarks");

            // 组织操作记录信息
            StringBuilder sb = new StringBuilder();
            sb.append(strDate).append(", 由").append(loginUser.getUsername()).append("关闭");

            Map<String, Object> map = new HashMap<>();
            map.put("ppid", id);
            map.put("recorddesc", sb.toString());
            map.put("recordremarks", closeRemarks);

            // 插入操作记录信息
            handlerService.insert("gq_proproblemrecord", map);

            // 更新问题状态
            handlerService.updateBySql("update gq_proproblem set status = '已关闭' where id = " + id);
        }

        // 解决问题
        if ("quoteproproblem1App".equals(app) && "gq_proproblem".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");

            // 更新问题状态
            handlerService.updateBySql("update gq_proproblem set status = '已解决' where id = " + id);

            // 转移附件
            // 查询项问题解决附件信息
            List<Map<String, Object>> attachList = handlerService.findBySql("select * from tb_file where appname = '" + app + "' and recordid = " + id);

            if (CollectionUtils.isNotEmpty(attachList)) {
                // 查询项目台账app信息
                BizApp bizApp = cfgRedisCache.getCacheApp("proproblemApp");
                Long appId = bizApp.getId();

                for (Map<String, Object> attachMap : attachList) {
                    Map<String, Object> addMap = new HashMap<>();
                    addMap.putAll(attachMap);
                    addMap.remove("fileid");
                    addMap.put("appid", appId);
                    addMap.put("appname", "proproblemApp");
                    addMap.put("recordid", id);

                    handlerService.insert("tb_file", addMap);
                }
            }
        }
    }
}
